import React, { createContext, useMemo, useState } from "react";
import { IServiceConfig, IServiceResponse, IServiceSendOptions, TypeRuningEnv } from "./ElmerService";

interface IApiHandlerOptions {
    sendOptions: IServiceSendOptions;
    isError: boolean;
    extra?: any;
    preventDefault: boolean;
}

export type IApiHandle = (data: any, response: IServiceResponse, options: IApiHandlerOptions) => any;

export interface IServiceContext<ENV> {
    config: IServiceConfig<ENV>;
    handler: IApiHandle[];
}

export const ServiceContext = createContext<IServiceContext<keyof TypeRuningEnv>>({} as any);


export const createService = <ENV extends keyof TypeRuningEnv>(config: IServiceConfig<ENV>, responseHandle?: IApiHandle[]): React.ComponentType<any> => {
    const newConfig = {...config, env: config.env || "PROD"};
    return ({children}: any) => {
        const [ configData ] = useState(newConfig);
        const serviceContext = useMemo(() => ({
            config: configData as any,
            handler: responseHandle ?? []
        }), [configData]);
        return <ServiceContext.Provider value={serviceContext}>{children}</ServiceContext.Provider>
    };
}
